package com.ztorn.fiscale.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletResponse;

import com.ztorn.common.core.constant.UserConstants;
import com.ztorn.common.core.utils.StringUtils;
import com.ztorn.common.core.utils.poi.ExcelUtil;
import com.ztorn.common.core.web.controller.BaseController;
import com.ztorn.common.core.web.domain.AjaxResult;
import com.ztorn.common.core.web.page.TableDataInfo;
import com.ztorn.common.log.annotation.Log;
import com.ztorn.common.log.enums.BusinessType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ztorn.fiscale.domain.FiscaleOrder;
import com.ztorn.fiscale.service.IFiscaleOrderService;

/**
 * 订单管理Controller
 *
 * @author ztorn
 * @date 2025-01-18
 */
@RestController
@RequestMapping("/order")
public class FiscaleOrderController extends BaseController
{
    @Autowired
    private IFiscaleOrderService fiscaleOrderService;

    /**
     * 查询订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(FiscaleOrder fiscaleOrder, @RequestParam(required = false) String orderIds)
    {
        startPage();

        // 处理订单ID数组参数
        if (StringUtils.isNotEmpty(orderIds)) {
            String[] orderIdArray = orderIds.split(",");
            Long[] orderIdLongs = new Long[orderIdArray.length];
            for (int i = 0; i < orderIdArray.length; i++) {
                orderIdLongs[i] = Long.parseLong(orderIdArray[i].trim());
            }
            fiscaleOrder.setOrderIds(orderIdLongs);
        }

        List<FiscaleOrder> list = fiscaleOrderService.selectFiscaleOrderList(fiscaleOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FiscaleOrder fiscaleOrder)
    {
        List<FiscaleOrder> list = fiscaleOrderService.selectFiscaleOrderList(fiscaleOrder);
        ExcelUtil<FiscaleOrder> util = new ExcelUtil<FiscaleOrder>(FiscaleOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:query')")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        return success(fiscaleOrderService.selectFiscaleOrderByOrderId(orderId));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FiscaleOrder fiscaleOrder)
    {
        // 校验订单号唯一性
        if (StringUtils.isNotEmpty(fiscaleOrder.getOrderNo()) &&
            UserConstants.NOT_UNIQUE==fiscaleOrderService.checkOrderNoUnique(fiscaleOrder.getOrderNo(), null))
        {
            return error("新增订单失败，订单号已存在");
        }

        // 标记为手动补录
        fiscaleOrder.setIsManual(1);
        return toAjax(fiscaleOrderService.insertFiscaleOrder(fiscaleOrder));
    }

    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FiscaleOrder fiscaleOrder)
    {
        // 校验订单号唯一性
        if (StringUtils.isNotEmpty(fiscaleOrder.getOrderNo()) &&
            UserConstants.NOT_UNIQUE==fiscaleOrderService.checkOrderNoUnique(fiscaleOrder.getOrderNo(), fiscaleOrder.getOrderId()))
        {
            return error("修改订单失败，订单号已存在");
        }

        return toAjax(fiscaleOrderService.updateFiscaleOrder(fiscaleOrder));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(fiscaleOrderService.deleteFiscaleOrderByOrderIds(orderIds));
    }

    /**
     * 根据订单号查询订单
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:query')")
    @GetMapping("/getByOrderNo/{orderNo}")
    public AjaxResult getByOrderNo(@PathVariable String orderNo)
    {
        FiscaleOrder order = fiscaleOrderService.selectFiscaleOrderByOrderNo(orderNo);
        return success(order);
    }

    /**
     * 根据平台订单号查询订单
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:query')")
    @GetMapping("/getByPlatformOrderNo/{platformOrderNo}")
    public AjaxResult getByPlatformOrderNo(@PathVariable String platformOrderNo)
    {
        FiscaleOrder order = fiscaleOrderService.selectFiscaleOrderByPlatformOrderNo(platformOrderNo);
        return success(order);
    }

    /**
     * 批量更新订单状态
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:edit')")
    @Log(title = "批量更新订单状态", businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdateStatus")
    public AjaxResult batchUpdateStatus(@RequestBody Map<String, Object> params)
    {
        Long[] orderIds = ((List<Integer>) params.get("orderIds")).stream()
                .mapToLong(Integer::longValue)
                .boxed()
                .toArray(Long[]::new);
        String orderStatus = (String) params.get("orderStatus");

        if (orderIds == null || orderIds.length == 0)
        {
            return error("请选择要更新的订单");
        }

        if (StringUtils.isEmpty(orderStatus))
        {
            return error("订单状态不能为空");
        }

        int result = fiscaleOrderService.batchUpdateOrderStatus(orderIds, orderStatus);
        return toAjax(result);
    }

    /**
     * 批量更新报关状态
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:customs')")
    @Log(title = "批量更新报关状态", businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdateCustomsStatus")
    public AjaxResult batchUpdateCustomsStatus(@RequestBody Map<String, Object> params)
    {
        Long[] orderIds = ((List<Integer>) params.get("orderIds")).stream()
                .mapToLong(Integer::longValue)
                .boxed()
                .toArray(Long[]::new);
        String customsStatus = (String) params.get("customsStatus");

        if (orderIds == null || orderIds.length == 0)
        {
            return error("请选择要更新的订单");
        }

        if (StringUtils.isEmpty(customsStatus))
        {
            return error("报关状态不能为空");
        }

        int result = fiscaleOrderService.batchUpdateCustomsStatus(orderIds, customsStatus);
        return toAjax(result);
    }

    /**
     * 生成报关单
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:customs')")
    @Log(title = "生成报关单", businessType = BusinessType.INSERT)
    @PostMapping("/generateCustoms")
    public AjaxResult generateCustoms(@RequestBody Map<String, Object> params)
    {
        try {
            List<Integer> orderIdList = (List<Integer>) params.get("orderIds");
            Long[] orderIds = orderIdList.stream()
                    .mapToLong(Integer::longValue)
                    .boxed()
                    .toArray(Long[]::new);

            if (orderIds == null || orderIds.length == 0)
            {
                return error("请选择要生成报关单的订单");
            }

            // 获取报关单信息
            String declarationType = (String) params.get("declarationType");
            String tradeMode = (String) params.get("tradeMode");
            String transportMode = (String) params.get("transportMode");
            String departurePort = (String) params.get("departurePort");
            String destinationPort = (String) params.get("destinationPort");
            String exportDate = (String) params.get("exportDate");
            String remark = (String) params.get("remark");

            // 简单的生成报关单逻辑：更新订单的报关状态为"报关中"
            int result = fiscaleOrderService.batchUpdateCustomsStatus(orderIds, "declaring");

            if (result > 0) {
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("orderIds", orderIds);
                resultData.put("declarationType", declarationType);
                resultData.put("tradeMode", tradeMode);
                resultData.put("transportMode", transportMode);
                resultData.put("departurePort", departurePort);
                resultData.put("destinationPort", destinationPort);
                resultData.put("exportDate", exportDate);
                resultData.put("remark", remark);
                resultData.put("customsDeclarationNo", generateCustomsDeclarationNo());

                return success("报关单生成成功，共处理 " + result + " 个订单"+resultData);
            } else {
                return error("报关单生成失败");
            }
        } catch (Exception e) {
            return error("报关单生成失败：" + e.getMessage());
        }
    }

    /**
     * 生成报关单号
     */
    private String generateCustomsDeclarationNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return "CD" + sdf.format(new Date()) + String.format("%04d", (int)(Math.random() * 10000));
    }

    /**
     * 同步平台订单
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:sync')")
    @Log(title = "同步平台订单", businessType = BusinessType.UPDATE)
    @PostMapping("/syncPlatformOrders")
    public AjaxResult syncPlatformOrders(@RequestParam String platformType,
                                        @RequestParam(required = false) Long platformConfigId)
    {
        int result = fiscaleOrderService.syncPlatformOrders(platformType, platformConfigId);
        if (result > 0)
        {
            return success("同步成功，共同步 " + result + " 条订单数据");
        }
        else
        {
            return success("暂无新订单需要同步");
        }
    }

    /**
     * 获取订单统计信息
     */
    @PreAuthorize("@ss.hasPermi('fiscale:order:query')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        Map<String, Object> statistics = new HashMap<>();

        // 按状态统计
        List<FiscaleOrder> statusStats = fiscaleOrderService.selectOrderCountByStatus();
        statistics.put("statusStats", statusStats);

        // 按平台统计
        List<FiscaleOrder> platformStats = fiscaleOrderService.selectOrderCountByPlatform();
        statistics.put("platformStats", platformStats);

        return success(statistics);
    }

    /**
     * 校验订单号是否唯一
     */
    @GetMapping("/checkOrderNoUnique")
    public AjaxResult checkOrderNoUnique(@RequestParam String orderNo,
                                        @RequestParam(required = false) Long orderId)
    {
        Boolean result = fiscaleOrderService.checkOrderNoUnique(orderNo, orderId);
        return success(UserConstants.UNIQUE==result);
    }
}
